package cn.itliuliu.org.service.impl;

import cn.itliuliu.basic.exception.CustomException;
import cn.itliuliu.org.domain.Employee;
import cn.itliuliu.org.domain.Shop;
import cn.itliuliu.org.mapper.EmployeeMapper;
import cn.itliuliu.org.mapper.ShopMapper;
import cn.itliuliu.org.service.IShopService;
import cn.itliuliu.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Wangtq
 * @since 2022-12-17
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 店铺入住
     *
     * @param shop
     */
    @Override
    public void settle(Shop shop) {
        //参数校验 spring validation
        //两次密码是否一致
        if (!shop.getAdmin().getPassword().equals(shop.getAdmin().getComfirmPassword())) {
            throw new CustomException("密码不一致");
        }
        //校验店铺是否注册过
        Shop shopTmp = shopMapper.loadByName(shop.getName());
        if (shopTmp != null) {
            throw new CustomException("店铺已存在");
        }

        //初始化店铺状态
        shop.setState(0);
        //店铺初始化注册时间
        shop.setRegisterTime(new Date());
        //添加店铺
        shopMapper.insert(shop);

        //判断店长是否注册过
        //根据用户名查询用户对象
        Employee emp = employeeMapper.loadByUserName(shop.getAdmin().getUsername());
        //店长如果注册过并且是别的店铺的
        if (emp != null && emp.getShopId() != null) {
            throw new CustomException("店长已经存在");
        }
        //如果店长存在但是没有shopid就直接绑定本次shop的id
        if (emp != null) {
            //员工有，并且可以成为这次的店长
            emp.setShopId(shop.getId());    //用户的ShopId 关联绑定店铺的id
            shop.setAdminId(emp.getId());   //店铺的AdminId 关联绑定员工的id
        } else {
            //员工绑定店铺id
            emp = shop.getAdmin();
            emp.setShopId(shop.getId());
            //给新增的员工添加状态
            emp.setState(0);
            //添加员工
            employeeMapper.insert(emp);
            //给店铺绑定店长
            shop.setAdminId(emp.getId());
        }
        //更新店铺
        shopMapper.update(shop);

    }
}
